import copy
import os
import sys

import mysql.connector
from mysql.connector import Error

import Globals
import Utils


# def parse_args():
#     # 检查命令行参数数量是否小于6，如果是，则打印错误信息并退出程序
#     # 获取距离文件，时间文件，规格文件的名字
#     global distance_file, time_file, spec_file, stop_time, customer_num, iter_time
#     distance_file = sys.argv[1]
#     time_file = sys.argv[2]
#     spec_file = sys.argv[3]
#
#     # 从命令行参数中获取停止时间和客户数量
#     stop_time = int(sys.argv[5])
#     Globals.customer_num = int(sys.argv[6])
#     iter_time = int(sys.argv[7])


# 更新当前的有效前沿
def update_EP(new_chromosome):
    copy_chromosome = copy.deepcopy(new_chromosome)
    flag = False
    # 为新染色体计算盒子分数
    Utils.get_box(copy_chromosome)
    # 如果当前EP集合为空，则直接添加新染色体到EP集合中，并更新极值解
    if len(Globals.final_EP) == 0:
        # print(f"EP集合为空,添加染色体解决方案到EP中")
        # 更新极值解
        update_extreme(copy_chromosome)
        Globals.final_EP.append(copy_chromosome)
    # 如果EP不为空
    else:
        # 遍历EP集合中的每个染色体
        for chrom in Globals.final_EP:
            if Utils.is_better(chrom, copy_chromosome) or Utils.is_equal(chrom, copy_chromosome):
                return
        # 检查新染色体是否是极值解
        if Utils.is_extreme(copy_chromosome):
            # 更新EP中所有被新染色体支配的解，并添加新染色体到EP集合中
            update_extreme(copy_chromosome)
            #  将当前EP中比新染色体差的解决方案移除
            Globals.final_EP = [chrom for chrom in Globals.final_EP if not Utils.is_better(copy_chromosome, chrom)]
            Globals.final_EP.append(copy_chromosome)
        # 如果新染色体不是极值解
        else:
            # 但能支配EP中的某些解，则移除这些被支配的解
            updated_EP = [chrom for chrom in Globals.final_EP if not Utils.is_better(copy_chromosome, chrom)]
            if len(updated_EP) < len(Globals.final_EP):  # 如果列表长度变短了，说明有染色体被移除了
                flag = True
            Globals.final_EP = updated_EP

            if flag:
                # 添加新染色体到EP集合中
                Globals.final_EP.append(copy_chromosome)
            # 如果没有找到被新染色体支配的解
            else:
                is_insert = True
                # 但新染色体在某些盒子分数上优于EP中的解
                for chrom in Globals.final_EP:
                    if Utils.is_equal_box(chrom, copy_chromosome) or Utils.is_better_box(chrom, copy_chromosome):
                        is_insert = False
                        break
                # 也将新染色体添加到EP中
                if is_insert:
                    Globals.final_EP.append(copy_chromosome)


# 如果新染色体在某个目标上比当前记录的极值解更好，就更新这个极值解为新染色体
def preserve_extreme(chrome, index):
    if Globals.extreme[index].f[index] - chrome.f[index] > 0.000001:
        Globals.extreme[index] = chrome


# 遍历所有目标，使用preserve_extreme来更新每个目标上的极值解。
def update_extreme(new_chromosome):
    for i in range(Globals.FUNC_NUM):
        preserve_extreme(new_chromosome, i)


def connect_fetch():
    """连接到MySQL数据库并执行查询"""
    data_name = sys.argv[1]

    try:
        # 连接到数据库
        connection = mysql.connector.connect(
            host='localhost',  # 数据库主机地址
            database='vrpsdptw',  # 数据库名称
            user='vrpsdptw',  # 数据库用户名
            password='123456'  # 数据库密码
        )

        if connection.is_connected():
            # 执行一个查询
            cursor = connection.cursor()
            cursor.execute(f"SELECT id FROM process_table where data_name='{data_name}';")
            sql_result = cursor.fetchall()

            MOSL_process_id=sql_result[0][0]
            MOMA_process_id = sql_result[1][0]
            cursor.execute(f"SELECT result_name,data_name FROM process_table where id={MOSL_process_id};")
            sql_result = cursor.fetchall()
            MOSL_result = sql_result[0][0]
            data_name_without_split = sql_result[0][1]
            data_name = sql_result[0][1].split('_')

            # 读取数据集
            c_num = str(data_name[1])
            Globals.customer_num = int(data_name[1])
            c_type = str(data_name[2])
            w_type = str(data_name[3])
            dataset_path = '../SDPPTW_data/'
            distance = dataset_path + "test" + c_num + "-0-0-0-0.d" + c_type + ".tw" + w_type + "DistanceMatrix.dat"
            time1 = dataset_path + "test" + c_num + "-0-0-0-0.d" + c_type + ".tw" + w_type + "TimeMatrix.dat"
            specs = dataset_path + "test" + c_num + "-0-0-0-0.d" + c_type + ".tw" + w_type + "Specs_sdp.dat"
            Utils.get_data(distance, time1, specs)

            cursor.execute(f"SELECT result_name FROM process_table where id={MOMA_process_id};")
            MOMA_result = cursor.fetchall()[0][0]

            path = '../Result/'

            # 读MOSL路径数
            MOSL_result_txt = path + MOSL_result + '/final.txt'
            MOSL_length = 0
            with open(MOSL_result_txt, 'r') as file:
                for _ in file:
                    MOSL_length += 1

            # 读MOMA路径数
            MOMA_result_txt = path + MOMA_result + '/final.txt'
            MOMA_length = 0
            with open(MOMA_result_txt, 'r') as file:
                for _ in file:
                    MOMA_length += 1

            # 读取MOSL路径信息
            MOSL_folder = path + MOSL_result + '/final_route'
            MOSL_route_content = []
            for i in range(MOSL_length):
                index = i + 1
                route_file_name = MOSL_folder + '/' + f"route{index}.txt"
                file_data = []
                with open(route_file_name, 'r') as file:
                    for index, line in enumerate(file):
                        if index % 2 == 0:
                            row = [int(val) for val in line.split()]
                            file_data.append(row)
                MOSL_route_content.append(file_data)

            # 将MOSL路径信息生成染色体
            for i in range(MOSL_length):
                solution = MOSL_route_content[i]
                choromsome = Globals.Chromosome()
                for j in range(len(solution)):
                    route = solution[j]
                    new_route = Globals.Route()
                    for cust in route:
                        new_route.customers.append(cust)
                    Utils.get_distance(new_route)
                    Utils.get_time(new_route)
                    choromsome.routes.append(new_route)
                Utils.get_f(choromsome)
                Globals.MOSL_EP.append(choromsome)
                update_EP(choromsome)

            # 读取MOMA路径信息
            MOMA_folder = path + MOMA_result + '/final_route'
            MOMA_route_content = []
            for i in range(MOMA_length):
                index = i + 1
                route_file_name = MOMA_folder + '/' + f"route{index}.txt"
                file_data = []
                with open(route_file_name, 'r') as file:
                    for index, line in enumerate(file):
                        if index % 2 == 0:
                            row = [int(val) for val in line.split()]
                            file_data.append(row)
                MOMA_route_content.append(file_data)

            # 将MOMA路径信息生成染色体
            for i in range(MOMA_length):
                solution = MOMA_route_content[i]
                choromsome = Globals.Chromosome()
                for j in range(len(solution)):
                    route = solution[j]
                    new_route = Globals.Route()
                    for cust in route:
                        new_route.customers.append(cust)
                    Utils.get_distance(new_route)
                    Utils.get_time(new_route)
                    choromsome.routes.append(new_route)
                Utils.get_f(choromsome)
                Globals.MOMA_EP.append(choromsome)
                update_EP(choromsome)

            result_path = 'refer/' + data_name_without_split + '.txt'
            with open(result_path, 'w') as file:
                Utils.output(file)

            result_route_path = 'refer/' + data_name_without_split + '_route'
            os.makedirs(result_route_path, exist_ok=True)
            for j, chromo in enumerate(Globals.final_EP):
                full_out_path = os.path.join(result_route_path, f"route{j + 1}.txt")
                with open(full_out_path, 'w') as f:
                    for route in chromo.routes:
                        route_row = " ".join(map(str, route.customers))
                        # 将每一行写入文件
                        f.write(route_row + "\n")

                        data = [len(route.customers) - 2, int(route.travel_dist), int(route.travel_time),
                                int(route.wait_time),
                                int(route.delay_time), int(route.delivery_capacity), int(route.pick_up_capacity)]
                        route_row = " ".join(map(str, data))
                        f.write(route_row + "\n")










    except Error as e:
        print("连接或查询过程中出现错误：", e)


if __name__ == '__main__':
    connect_fetch()
